﻿
using SqlSugar;
using SqlsugarService.Infrastructure.IRepository;
using System.Linq.Expressions;

namespace SqlsugarService.Infrastructure.Repository
{
    /// <summary>
    /// 基础仓储实现
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    public class BaseRepository<T> : SimpleClient<T>, IBaseRepository<T> where T : class, new()
    {
        public BaseRepository(ISqlSugarClient db)
        {
            base.Context = db;
        }

        #region 查询操作

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        public virtual async Task<T?> GetByIdAsync(object id)
        {
            return await Context.Queryable<T>().InSingleAsync(id);
        }

        /// <summary>
        /// 根据条件获取单个实体
        /// </summary>
        public virtual async Task<T?> GetFirstAsync(Expression<Func<T, bool>> whereExpression)
        {
            return await Context.Queryable<T>().FirstAsync(whereExpression);
        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        public virtual async Task<List<T>> GetAllAsync()
        {
            return await Context.Queryable<T>().ToListAsync();
        }

        /// <summary>
        /// 根据条件获取列表
        /// </summary>
        public virtual async Task<List<T>> GetListAsync(Expression<Func<T, bool>> whereExpression)
        {
            return await Context.Queryable<T>().Where(whereExpression).ToListAsync();
        }


        #endregion

        #region 分页查询
        /// <summary>
        /// 分页查询（字符串排序）
        /// </summary>
        public virtual async Task<(List<T> Data, int TotalCount)> GetPagedAsync(
            int pageIndex,
            int pageSize,
            Expression<Func<T, bool>>? whereExpression = null,
            string orderBy = "Id desc")
        {
            var query = Context.Queryable<T>();

            if (whereExpression != null)
            {
                query = query.Where(whereExpression);
            }

            // 获取总数
            var totalCount = await query.CountAsync();

            // 分页
            var data = await query
                .OrderBy(orderBy)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return (data, totalCount);
        }

        #endregion

        #region 新增操作

        /// <summary>
        /// 新增单个实体
        /// </summary>
        public virtual async Task<bool> InsertAsync(T entity)
        {
            return await Context.Insertable(entity).ExecuteCommandAsync() > 0;
        }
        
        /// <summary>
        /// 批量新增
        /// </summary>
        public virtual async Task<bool> InsertRangeAsync(List<T> entities)
        {
            return await Context.Insertable(entities).ExecuteCommandAsync() > 0;
        }


        #endregion

        #region 更新操作

        /// <summary>
        /// 更新实体
        /// </summary>
        public virtual async Task<bool> UpdateAsync(T entity)
        {
            return await Context.Updateable(entity).ExecuteCommandAsync() > 0;
        }


        /// <summary>
        /// 批量更新
        /// </summary>
        public virtual async Task<bool> UpdateRangeAsync(List<T> entities)
        {
            return await Context.Updateable(entities).ExecuteCommandAsync() > 0;
        }

        #endregion


        #region 软删除操作（如果实体支持）

        /// <summary>
        /// 软删除（需要实体有IsDeleted字段）
        /// </summary>
        public virtual async Task<bool> SoftDeleteAsync(object id)
        {
            return await Context.Updateable<T>()
                .SetColumns("IsDeleted = @isDeleted", new { isDeleted = true })
                .Where("Id = @id", new { id })
                .ExecuteCommandAsync() > 0;
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        public virtual async Task<bool> SoftDeleteRangeAsync(object[] ids)
        {
            return await Context.Updateable<T>()
                .SetColumns("IsDeleted = @isDeleted", new { isDeleted = true })
                .Where($"Id in ({string.Join(",", ids)})")
                .ExecuteCommandAsync() > 0;
        }

        #endregion

    }
}
